package org.example.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import org.example.common.entity.User;
import org.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/jwt")
public class LoginController {

    @Autowired
    private UserService userService;

    // 会话登录接口
    @PostMapping("login")
    public SaResult doLogin(@RequestBody User user) {
        // 第一步：比对前端提交的账号名称、密码
        User dbUser = userService.selectUserByUsername(user);
        if(dbUser != null && !dbUser.getUserId().equals(null)) {
            // 第二步：根据账号id，进行登录
            StpUtil.login(dbUser.getUserId());
            return SaResult.ok("登录成功").setData(StpUtil.getTokenValue());
        }
        return SaResult.error("登录失败");
    }

    @PostMapping("logout")
    public SaResult logout() {
        StpUtil.logout();
        return SaResult.ok("退出成功");
    }

    @PostMapping("getUserInfo")
    public SaResult getUserInfo() {
        Long userId = StpUtil.getLoginIdAsLong();
        User user = userService.selectUserById(userId);
        return SaResult.ok().setData(user);
    }

    @PostMapping("refreshToken")
    public SaResult refreshToken() {
        // 先检查是否已被冻结
        StpUtil.checkActiveTimeout();
        StpUtil.updateLastActiveToNow();
        return SaResult.ok("刷新成功");
    }

}
